package pers.qianyu.month_202012.date_20201202;

import java.util.*;
import java.util.stream.*;

/**
 * 402. 移掉K位数字
 * https://leetcode-cn.com/problems/remove-k-digits/
 *
 * @author mizzle rain
 * @date 2020-12-02 19:54
 */
public class RemoveKdigits {
    public String removeKdigits(String num, int k) {
        Stack<Character> stack = new Stack<>();
        int remain = num.length() - k;
        if (remain == 0) {
            return "0";
        }
        for (int i = 0; i < num.length(); i++) {
            char c = num.charAt(i);
            while (!stack.isEmpty() && stack.peek() > c && k > 0) {
                stack.pop();
                k--;
            }
            stack.push(c);
        }
        String text = stack.stream()
                .map(String::valueOf)
                .collect(Collectors.joining(""));
        String res = text.length() > remain ? text.substring(0, remain) : text;
        return ltrip(res);
    }

    /**
     * 去掉左侧的 "0"
     *
     * @param res
     * @return
     */
    private String ltrip(String res) {
        StringBuilder builder = new StringBuilder(res);
        while (builder.length() > 0 && builder.charAt(0) == '0') {
            builder.deleteCharAt(0);
        }
        return builder.length() == 0 ? "0" : builder.toString();
    }

    public static void main(String[] args) {
        String result = new RemoveKdigits().removeKdigits("9", 1);
        System.out.println("result = " + result);
    }
}
